//
//  GuideViewController.m
//  Marketing
//
//  Created by 邹奥 on 16/8/16.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "GuideViewController.h"
#import "AppDelegate.h"
#import "WebViewController.h"

@interface GuideViewController () {
    UIImageView         *_bgImgView;
    NSTimer             *_registerTimer;
    int                 register_timerCount;
    UIButton            *timeBt;
    NSMutableDictionary *_selectDic;
}

@end
@implementation GuideViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _selectDic = [[NSMutableDictionary alloc]init];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self onCreateUI];
    
    [self onLoadApp];
}

- (void)onCreateUI
{
    _bgImgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    _bgImgView.backgroundColor = [UIColor whiteColor];
    _bgImgView.userInteractionEnabled = YES;
    [self.view addSubview:_bgImgView];
    NSString *picPath = [MusicCachesDirectory stringByAppendingPathComponent:@"lunbo.png"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:picPath]) {
        //加载缓存图片
       // _bgImgView.image = [UIImage imageWithContentsOfFile:picPath];

    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTapTurnToView)];
    [_bgImgView addGestureRecognizer:tap];
    
    timeBt = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBt.frame = CGRectMake(SCREEN_WIDTH-80, 25, 70, 30);
    timeBt.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.45];
    [timeBt setTitle:@"" forState:UIControlStateNormal];
    [timeBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [timeBt.titleLabel setFont:[UIFont systemFontOfSize:12.f]];
    timeBt.layer.cornerRadius = 15;
    timeBt.layer.masksToBounds = YES;
    [timeBt addTarget:self action:@selector(onDeleteAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:timeBt];
    [self.view insertSubview:timeBt aboveSubview:_bgImgView];
    
}

- (void)onLoadApp
{
    NSString *url = [NSString stringWithFormat:@"https://app.vooda.co/Portal/App.aspx?app=29"];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(NSDictionary *json) {
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"result"] boolValue] == YES) {
                [self loadData];
            } else {
                //推出程序
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                UIWindow *window = app.window;
                
                [UIView animateWithDuration:1.0f animations:^{
                    window.alpha = 0;
                    window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
                } completion:^(BOOL finished) {
                    exit(0);
                }];
            }
        }
    } failure:^(NSError *error) {
        [self loadData];
    }];
}

- (void)loadData
{
    NSString *url = [NSString stringWithFormat:STORY_HOT_GETPIC_LIST_AUDIOLIST_URL_PATH,@2];
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(NSDictionary *json) {
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if ([arr isKindOfClass:[NSArray class]]) {
                    NSDictionary *dic = [arr firstObject];
                    [_selectDic removeAllObjects];
                    [_selectDic addEntriesFromDictionary:dic];
                    
                    NSString *FigurePath = [dic objectForKey:@"FigurePath"];
                    NSString *FigurePath2 = [dic objectForKey:@"FigurePath2"];
                    if (![FigurePath isKindOfClass:[NSNull class]]) {
                        if (ISIPAD) {
                            [_bgImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,FigurePath2]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                //倒计时
                                register_timerCount = 5;
                                [self onSendPhoneAction];
                                
                                NSString *picPath = [MusicCachesDirectory stringByAppendingPathComponent:@"lunbo.png"];
                                NSData *data = UIImagePNGRepresentation(image);
                                [data writeToFile:picPath atomically:YES];
                            }];

                        }else{
                        [_bgImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,FigurePath]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                            //倒计时
                            register_timerCount = 5;
                            [self onSendPhoneAction];
                            
                            NSString *picPath = [MusicCachesDirectory stringByAppendingPathComponent:@"lunbo.png"];
                            NSData *data = UIImagePNGRepresentation(image);
                            [data writeToFile:picPath atomically:YES];
                        }];
                        }
                        
                    }
                }
            }
        }
    } failure:^(NSError *error) {
       [self onDeleteAction];
    }];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _bgImgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    timeBt.frame = CGRectMake(SCREEN_WIDTH-80, 25, 70, 30);
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeRight|UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskPortraitUpsideDown;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationMaskLandscapeRight|UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskPortraitUpsideDown;
}

//获取验证码
- (void)onSendPhoneAction
{
    if (!_registerTimer) {
        _registerTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onCountDownAction) userInfo:self repeats:YES];
        [[NSRunLoop mainRunLoop]addTimer:_registerTimer forMode:NSDefaultRunLoopMode];
    }
}

//倒计时
- (void)onCountDownAction
{
    if (register_timerCount == 0) {
        [timeBt setTitle:@"获取" forState:UIControlStateNormal];
        [_registerTimer invalidate];
        _registerTimer = nil;
        
        [self onDeleteAction];
        return;
    }
    [timeBt setTitle:[NSString stringWithFormat:@"%ds跳过",register_timerCount] forState:UIControlStateNormal];
    register_timerCount--;
}

//跳转下一页面
- (void)onDeleteAction
{
    if (_registerTimer) {
        [_registerTimer invalidate];
        _registerTimer = nil;
    }
    
    BOOL isTabbar = YES;
    if ([FIRST_GUIDE_SHOW length] == 0) {
        //第一次启动，显示引导
        isTabbar = NO;
    }
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate setUpTabbar:isTabbar];

}

- (void)onTapTurnToView
{
    NSString *status = [_selectDic objectForKey:@"FigureStatus"];
    if ([status intValue] == 1) {
        WebViewController *web = [[WebViewController alloc]init];
        web.dataDic = _selectDic;
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.window.rootViewController = web;
        
        if (_registerTimer) {
            [_registerTimer invalidate];
            _registerTimer = nil;
        }
    }
}

@end
